package myJs.admin

import myJs.{App, MyPages}
import myJs.cps.{PureInputCp, Style}
import myJs.myPkg.ReactRouterDOM
import org.scalajs.dom.{Event, window}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.web.html._
import myJs.Implicits._

/**
 * Created by yz on 21/1/2022
 */
@react object TagCp {

  type Props = Unit

  val component = FunctionalComponent[Props] { props =>

    val initActivePage = None: Option[MyPages]
    val (activePage, setActivePage) = useState(initActivePage)
    val (myPages, setMyPages) = useState(List.empty[MyPages])
    val location = ReactRouterDOM.useLocation()

    useEffect(() => {
      addTag
    }, List(location)
    )

    def addTag = {
      val curPath = window.location.href.replaceAll(".*/#/"+Admin.prefix+"/", "")
      val usePages = Admin.pages
      val curPageOp = usePages.find { x =>
        x.path == curPath
      }
      val newMyPages = curPageOp.map { curPage =>
        if (myPages.contains(curPage)) myPages else myPages :+ curPage
      }.getOrElse(myPages)
      setMyPages(newMyPages)
      setActivePage(curPageOp)
    }

    def deleteMyPage(myPage: MyPages) = (e: SyntheticEvent[TagElement#RefType, Event]) => {
      e.preventDefault()
      val remainPages = myPages.removed(myPage)
      val curActivePage = activePage.map { myPage =>
        if (remainPages.contains(myPage)) activePage else remainPages.lastOption
      }.getOrElse {
        remainPages.lastOption
      }
      setMyPages(myPages.removed(myPage))
      setActivePage(curActivePage)
      curActivePage.foreach { myPage =>
        window.location.href = s"#/${Admin.prefix}/${myPage.path}"
      }
    }

    div(className := "tags-view-container",
      div(className := "scroll-container tags-view-wrapper",
        div(className := "scroll-wrapper",
          myPages.map { myPage =>
            val activeStr = activePage.map { page =>
              if (page == myPage) "active" else ""
            }.getOrElse("")
            a(key := s"${myPage.path}", href := s"#/${Admin.prefix}/${myPage.path}",
              className := s"tags-view-item myHistoryLinkA ${activeStr}",
              myPage.titleStr,
              span(className := "fa fa-close", onClick := deleteMyPage(myPage))
            )
          }
        )
      )
    )


  }


}
